package cn.qingyun.gis.modules.scenes.util;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;

import java.util.*;
import java.util.stream.Collectors;

@SuppressWarnings("ALL")
public class RoomComplexShardingAlgorithm implements ComplexKeysShardingAlgorithm {
    private static final List<String> CITIES = Lists.newArrayList("SD.LA", "SD.LB", "SD.LC", "SD.LD", "SD.LE", "SD.LF", "SD.LG", "SD.LH", "SD.LI", "SD.LJ", "SD.LK", "SD.LL", "SD.LM", "SD.LN", "SD.LO", "SD.LQ");

    @Override
    public Collection<String> doSharding(Collection collection, ComplexKeysShardingValue complexKeysShardingValue) {
        Map<String, Collection<?>> shardingValues = complexKeysShardingValue.getColumnNameAndShardingValuesMap();
        Collection<String> cityCodes = getFilteredCityCodes(shardingValues);
        Collection<String> result = new LinkedHashSet<>();

        for (Object cityCode : cityCodes) {
            result.add("poi_scenario_"+ String.valueOf(cityCode).substring(3).toLowerCase());
        }
        return result;
    }
    private Collection<String> getFilteredCityCodes(Map<String, Collection<?>> shardingValues) {
        Collection<String> cityCodes = shardingValues.getOrDefault("region_city_code", Collections.emptyList())
                .stream()
                .filter(item -> item instanceof String && CITIES.contains(item))
                .map(item -> (String) item)
                .collect(Collectors.toList());

        if (cityCodes.isEmpty()) {
            cityCodes = CollUtil.newArrayList(CITIES);
        }
        return cityCodes;
    }
}
